import traceback

import time

import os

import xlrd

from common.request import requestutil
from common.utils.coordinate import get_location, geodistance
from common.utils.outputgenerater import to_excel
from config import config
from lianjia.excel_db import Excel

geo_人民广场 = (31.232781, 121.475137)
geo_汉口汇丰银行大楼 = (30.581181, 114.299669)


def getHouseList(url):
    resp = requestutil.get(url, timeout=4)
    items = resp.html.find("#content > div.leftContent > ul > li")
    results = []

    for item in items:
        try:
            house = {}
            小区 = item.find("div.info.clear > div.flood > div > a:nth-child(2)")[0]
            小区编号 = 小区.attrs["href"].replace(r"https://wh.lianjia.com/xiaoqu/", "").replace(r"/", "")
            house["房源编号"] = item.find("div.info.clear > div.title > a")[0].attrs["data-housecode"]
            house["小区编号"] = 小区编号
            house["小区名称"] = 小区.text.split(r"|")[0]
            house["房源信息"] = item.find("div.info.clear > div.address > div")[0].text
            house["总价"] = item.find("div.info.clear > div.priceInfo > div.totalPrice > span")[0].text
            house["单价"] = item.find("div.info.clear > div.priceInfo > div.unitPrice > span")[0].text
            results.append(house)
        except Exception:
            print(traceback.format_exc())
    return results


def getHouseExcel():
    results = []
    url = "https://wh.lianjia.com/ershoufang/pg%sco32/"
    for i in range(1, 99):
        try:
            result = getHouseList(url % str(i))
            results.extend(result)
            time.sleep(1)
        except:
            pass
    return results


def save(results):
    eHouse = Excel(config.PATH_DESKTOP + os.path.sep + "房源数据.xls", "房源")

    for r in results:
        eHouse.add(r)
    eHouse.save()

    eXiaoqu = Excel(config.PATH_DESKTOP + os.path.sep + "小区数据.xls", "小区")
    for r in results:
        xq = {}
        xq["小区名称"] = r["小区名称"]
        xq["小区编号"] = r["小区编号"]
        eXiaoqu.updateOrAdd({"小区编号": r["小区编号"]}, xq)
    eXiaoqu.save()


def fillLocation():
    eXiaoqu = Excel(config.PATH_DESKTOP + os.path.sep + "小区数据.xls", "小区")

    for r in eXiaoqu.getData():
        小区名称 = r["小区名称"]
        geo1 = get_location(小区名称, "武汉")
        r["坐标"] = str(geo1)
        r["离市中心距离"] = geodistance(geo1, geo_汉口汇丰银行大楼)
        eXiaoqu.updateOrAdd({"小区编号": r["小区编号"]}, r)
    eXiaoqu.save()


if __name__ == '__main__':
    # results = getHouseExcel()
    # save(results)
    fillLocation()
